<?php

namespace App\Http\Controllers\Admins\Activity;

use App\Http\Controllers\Admins\BaseAdminController;
use App\Models\Activity;
use App\Models\ActivityOrders;
use App\Models\ActivityOrdersCommon;
use App\Models\OperationalLogs;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\View\Factory;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ActivityController extends BaseAdminController
{
    /**
     * 活动列表
     * @param Request $request
     * @return array|Application|Factory|View
     *
     */
    public function index(Request $request){
        $condition = $request->get('condition','name');
        if($request->isMethod('post')){
            # 要执行的代码
            $query = Activity::query()->latest();
            $keywords = $request->get('keywords',null);
            if ($keywords) {
                $query->where($condition, 'like', '%' . $keywords . '%');
            }
            $status = $request->get('status','all');
            if($status != 'all'){
                $query->where('status', $status);
            }
            $pageSize = $request->get('limit',10);
            # 计算offset值
            $offset = $request->get('offset',0);
            # 总数
            $total = $query->count();
            $data = $query->limit($pageSize)->offset($offset)->get();
            $result = array();
            if($data){
                foreach($data as $val){
                    $result[] = Activity::getDataByID($val['id']);
                }
            }
            return ret([
                'total'=>$total,
                'data'=>$result
            ]);
        }
        $admin_id = $request->get('admin_id');
        $subtitle = '活动管理';
        $compact = compact('subtitle','admin_id');
        return view('v1.admin.activity.index',$compact);
    }

    /**
     * 创建活动
     *
     * @param Request $request
     * @return Application|Factory|View|RedirectResponse
     */
    public function add(Request $request)
    {
        if($request->isMethod('post')) {
            $admin_id = $request->get('admin_id');
            $table = 'activity';
            #表单验证
            $validator = AdminFormVerify($table, $request);
            if ($validator->fails()) {
                return $this->retError($validator,$request);
            }
            $name = $request->get('name');
            $post = $request->all();
//            dd($post);
            unset($post['_token']);
            $signup_status = Activity::computeStatusByTime($post['signup_start_at'],$post['signup_end_at'],true);
            $post['signup_status'] = $signup_status;
            $status = Activity::computeStatusByTime($post['start_at'],$post['end_at']);
            $post['status'] = $status;
            $create = $post;
            $logs = [
                'admin_id' => $admin_id,
                'operate_menu' => OperationalLogs::$operateItem['activity_manage'],
                'operate_item' => $name,
                'operate_content' => '创建活动：' . $name,
            ];
            DB::beginTransaction();
            try {
                $create['remaining_counts'] = $post['total_counts'];
                Activity::query()->create($create);
                #操作日志
                OperationalLogs::AddOperationalLogs($logs);
                DB::commit();
                return $this->retSuccess();
            } catch (\Exception $exception) {
                DB::rollback();
                return $this->retError($exception->getMessage(),$request);
            }
        }
        $url = route('v1.admin.activity.index');
        $params = [
            'url'=>$url,
            'success'=>'success'
        ];
        $subtitle = '创建活动';
        $view = 'v1.admin.activity.add';
        $compact = compact('subtitle','params');
        return view($view,$compact);
    }

    /**
     * 查看活动
     *
     * @param Request $request
     * @param $id
     * @return Application|Factory|View|RedirectResponse
     */
    public function show(Request $request,$id)
    {
        $model = Activity::query();
        $where = [
            'id'=>$id
        ];
        $model_query = AdminModelQuery($id,$model,$where);
        if($model_query['code'] == 0){
            return  $this->retError($model_query['msg'],$request);
        }
        $subtitle = '查看活动';
        $view = 'v1.admin.activity.show';
        $data = Activity::getDataByID($id);
        $compact = compact('subtitle','data');
        return view($view,$compact);
    }
    /**
     * 编辑活动
     *
     * @param Request $request
     * @param $id
     * @return Application|Factory|View|RedirectResponse
     */
    public function edit(Request $request,$id)
    {
        $model = Activity::query();
        $where = [
            'id'=>$id
        ];
        $model_query = AdminModelQuery($id,$model,$where);
        if($model_query['code'] == 0){
            return  $this->retError($model_query['msg'],$request);
        }
        if($request->isMethod('post')) {
            $admin_id = $request->get('admin_id');
            $table = 'activity';
            $validator = AdminFormVerify($table, $request, 'update');
            if ($validator->fails()) {
                return $this->retError($validator,$request);
            }
            $name = $request->get('name');
            $where_unique = [
                'name'=>$name,
            ];
            $Model = Activity::query();
            $data_unique = AdminUpdateDataUniqueVerify($Model,$id,$where_unique);
            if($data_unique['code'] == 201){
                return $this->retError($data_unique['msg'],$request);
            }
            $post = $request->all();
            unset($post['_token']);
            unset($post['id']);
            $signup_status = Activity::computeStatusByTime($post['signup_start_at'],$post['signup_end_at'],true);
            $post['signup_status'] = $signup_status;
            $status = Activity::computeStatusByTime($post['start_at'],$post['end_at']);
            $post['status'] = $status;
            $update = $post;
            $logs = [
                'admin_id' => $admin_id,
                'operate_menu' => OperationalLogs::$operateItem['activity_manage'],
                'operate_item' => $name,
                'operate_content' => '修改活动：' . $name,
            ];
            DB::beginTransaction();
            try {
                Activity::query()->where('id', $id)->update($update);
                #操作日志
                OperationalLogs::AddOperationalLogs($logs);
                DB::commit();
                return $this->retSuccess();
            } catch (\Exception $exception) {
                DB::rollback();
                return $this->retError($exception->getMessage(), $request);
            }
        }
        $url = route('v1.admin.activity.index');
        $params = [
            'url'=>$url,
            'success'=>'success'
        ];
        $subtitle = '编辑活动';
        $view = 'v1.admin.activity.edit';
        $data = Activity::getDataByID($id);
        $compact = compact('subtitle','params','data');
        return view($view,$compact);
    }

    /**
     * 报名人员信息
     *
     * @param Request $request
     * @param $id
     * @return array|Application|Factory|View
     */
    public function signUpInfo(Request $request,$id)
    {
        $where = [
            'id'=>$id
        ];
        $condition = $request->get('condition','username');
        if($request->isMethod('post')){
            # 要执行的代码
            $query = Activity::query()->where($where)->latest();
            $keywords = $request->get('keywords',null);
            if ($keywords) {
                $query->where($condition, 'like', '%' . $keywords . '%');
            }
//            $status = $request->get('status','all');
//            if($status != 'all'){
//                $query->where('status', $status);
//            }
            $pageSize = $request->get('limit',10);
            # 计算offset值
            $offset = $request->get('offset',0);
            # 总数
            $total = $query->count();
            $data = $query->limit($pageSize)->offset($offset)->get();
            $result = array();
            if($data){
                foreach($data as $val){
                    $result[] = Activity::getDataByID($val['id']);
                }
            }
            return ret([
                'total'=>$total,
                'data'=>$result
            ]);
        }
        $admin_id = $request->get('admin_id');
        $subtitle = '活动管理';
        $compact = compact('subtitle','admin_id');
        return view('v1.admin.activity.index',$compact);

//        $model = Activity::query();
//        $where = [
//            'id'=>$id
//        ];
//        $model_query = AdminModelQuery($id,$model,$where);
//        if($model_query['code'] == 0){
//            return  $this->retError($model_query['msg'],$request);
//        }
//        $name = Activity::query()->where($where)->value('name');
//        $view = 'v1.admin.activity.signUpInfo';
//        $data = '';
//        $subtitle = '活动报名信息';
//        $compact = compact('subtitle','name','data');
//        return view($view,$compact);
    }

    /**
     * 删除
     *
     * @param Request $request
     * @param $id
     * @return array
     * @throws \Throwable
     */
    public function delete(Request $request,$id): array
    {
        $where = [
            'id'=>$id,
        ];
        $data = Activity::query()->where($where);
        $logs = [
            'admin_id'=>$request->get('admin_id'),
            'operate_menu'=>OperationalLogs::$operateItem['activity_manage'],
            'operate_item'=>Activity::query()->where($where)->value('name').'('.$id.')',
            'operate_content'=>OperationalLogs::$operate['activity_delete'],
        ];
        return AdminDeleteData($data,$logs);
    }

    public function usershow(Request $request,$id)
    {

        $where = [
            'activity_id' => $id
        ];

        $field = [
            'users.*',
            'activity_orders.order_num'
        ];

        $title = Activity::query()->where(['id'=>$id])->value('name');

        if($request->isMethod('post')){
            # 要执行的代码
            $query = ActivityOrders::query()
                ->leftjoin('users', 'activity_orders.user_id', '=', 'users.id')->where($where);
            $keywords = $request->get('keywords',null);

            $status = $request->get('status','all');
            if($status != 'all'){
                $query->where('status', $status);
            }
            $pageSize = $request->get('limit',10);
            # 计算offset值
            $offset = $request->get('offset',0);
            # 总数
            $total = $query->count();
            $data = $query->limit($pageSize)->offset($offset)->select($field)->get();
/*            $data = ActivityOrders::query()
                ->leftjoin('users', 'activity_orders.user_id', '=', 'users.id')
                ->where($where)
                ->select($field)
                ->get();*/
            $result = array();
            if($data){
                foreach($data as $val){
                    $result[] =$val;
                     // PostsComment::getDataByID($val['id']);
                }
            }
            return ret([
                'total'=>$total,
                'data'=>$result
            ]);
        }

        $admin_id = $this->admin_id;
        $post_id  = $id;
        $subtitle = '活动报名详情';
        return view('v1.admin.activity.users.index',compact('subtitle','admin_id','title','post_id'));
    }

    public function deleteuser(Request $request,$id)
    {
            //

           $info =  ActivityOrders::query()->where(['order_num'=>$id])->first();
            $cinfo = ActivityOrdersCommon::query()->where(['order_id'=>$info['id']])->first();
            if(!empty($info)  && !empty($cinfo)){
                //删除
                DB::beginTransaction();
                try {
                    $activity_id  =  $info['activity_id'];

                    $Activity = Activity::find($activity_id); // 假设要自增的用户ID为1
                    $Activity->increment('remaining_counts'); // 将指定字段的值自增1
                    $Activity->decrement('signup_counts'); // 将指定字段的值自减1

                    ActivityOrders::query()->where(['order_num'=>$id])->forceDelete();
                    ActivityOrdersCommon::query()->where(['order_id'=>$info['id']])->forceDelete();



                    DB::commit();
                    return AdminRet('操作成功!');
                } catch (\Exception $exception) {
                    DB::rollBack();
                    return AdminRetError($exception->getMessage());
                }
            }
        return  $this->retError('Error',$request);
    }
}
